﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace DCT.AutoUpdate.Code
{
    public static class FileUtility
    {
        public static string GetRealPath(string path)
        {
            path = path ?? "";

            path = Path.GetFullPath(path);
            
            return path;
        }

        public static bool MakeSureFileExist(string filepath)
        {
            bool create = false;
            if (!File.Exists(filepath))
            {
                string folder = Path.GetDirectoryName(filepath);
                if (!Directory.Exists(folder)) {
                    Directory.CreateDirectory(folder);
                }
                using (File.Create(filepath))
                {
                }
                create = true;
            }
            return create;
        }

        public static string CopyFileWithRenameWhenConfict(string source, string target)
        {
            string realTarget = "";
            RenameWhenFileExist(target, out realTarget);
            File.Copy(source, realTarget);

            return realTarget;
        }

        public static bool RenameWhenFileExist(string file, out string newfileName) {
            bool rename = false;
            newfileName = file;

            string fileNameWithoutExt = Path.GetFileNameWithoutExtension(newfileName);
            string ext = Path.GetExtension(newfileName);
            string folder = Path.GetDirectoryName(newfileName);

            int rollIndex = 0;

            while (File.Exists(newfileName))
            {
                rollIndex++;
                newfileName = Path.Combine(folder, fileNameWithoutExt + "(" + rollIndex.ToString() + ")" + ext);
            }
            rename = string.Compare(file, newfileName, true) != 0;

            return rename;
        }

        //private static void Test() {
        //    Console.WriteLine(CopyFileWithRenameWhenConfict(@"C:\Users\kimogigi\Desktop\Floor.txt", @"F:\xxx.txt"));
        //    Console.WriteLine(CopyFileWithRenameWhenConfict(@"C:\Users\kimogigi\Desktop\Floor.txt", @"F:\xxx.txt"));
        //    Console.WriteLine(CopyFileWithRenameWhenConfict(@"C:\Users\kimogigi\Desktop\Floor.txt", @"F:\xxx.txt"));
        //    Console.WriteLine(CopyFileWithRenameWhenConfict(@"C:\Users\kimogigi\Desktop\Floor.txt", @"F:\xxx.txt"));
        //    Console.WriteLine(CopyFileWithRenameWhenConfict(@"C:\Users\kimogigi\Desktop\Floor.txt", @"F:\xxx.txt"));
        //}
    }
}
